package com.example.blue;

import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.blue.ui.DynamicWaveFormView;

import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;

public class XiangjiActivity extends AppCompatActivity implements DataProcessorManager.DataUpdateListener{
    private static final String TAG = "PingjuActivity";
    private String deviceId;
    private BluetoothService bluetoothService;
    private boolean isBound=false;
    private Button btn;
    private Integer handDir;
    private ImageView imageView;
    private TextView shuomingText;
    private Boolean startFlag=false;
    private DynamicWaveFormView waveformViewX1;
    private DynamicWaveFormView waveformViewY1;
    private DynamicWaveFormView waveformViewZ1;
    private DynamicWaveFormView waveformViewX2;
    private DynamicWaveFormView waveformViewY2;
    private DynamicWaveFormView waveformViewZ2;
    private LinearLayout groupLayout;
    private DataProcessorManager processorManager;
    private ProgressDialog progressDialog;
    private List<String> saveData;

    private ConcurrentLinkedQueue<byte[]> dataQueue = new ConcurrentLinkedQueue<>();
    private final ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            BluetoothService.LocalBinder binder = (BluetoothService.LocalBinder) service;
            bluetoothService = binder.getService();
            isBound = true;
            Log.d("ServiceTest", "onServiceConnected: bound=" + isBound);
            dataQueue  = bluetoothService.getDataQueue();
//            if(dataQueue.isEmpty()){
//                new AlertDialog.Builder(XiangjiActivity.this)
//                        .setTitle("提示")
//                        .setMessage("未收到数据，请重试")
//                        .setPositiveButton("确定", (dialog, which) -> {
//                            finish();
//                        })
//                        .show();
//            }else {
                processorManager = DataProcessorManager.getInstance(dataQueue);
//            }
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            isBound = false;
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // EdgeToEdge.enable(this);
        setContentView(R.layout.activity_xiangji);
        // 开启返回箭头
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeAsUpIndicator(null);
        getSupportActionBar().setTitle("双手置于胸前手心向内测试");
        btn = findViewById(R.id.startBtn);
        SharedPreferences sp = getSharedPreferences("my_cache", Context.MODE_PRIVATE);
        deviceId = sp.getString("deviceId", "");
        System.out.println(deviceId);
        if (deviceId == "" || deviceId.isEmpty()) {
            Toast.makeText(XiangjiActivity.this,"未获取到蓝牙MAC地址，请重新连接",Toast.LENGTH_SHORT).show();
        }
        handDir = sp.getInt("handDir",1);
        imageView=findViewById(R.id.imageView);
        shuomingText=findViewById(R.id.shuoming);
        groupLayout=findViewById(R.id.group_container);
        waveformViewX1 = findViewById(R.id.waveformView1);
        waveformViewY1 = findViewById(R.id.waveformView2);
        waveformViewZ1 = findViewById(R.id.waveformView3);
        waveformViewX2 = findViewById(R.id.waveformView4);
        waveformViewY2 = findViewById(R.id.waveformView5);
        waveformViewZ2 = findViewById(R.id.waveformView6);
        waveformViewX1.setYtitle("加速度模值(传感器1)");
        waveformViewX1.setYRange(-20,20);
        waveformViewY1.setYtitle("加速度模值(传感器2)");
        waveformViewY1.setYRange(-20,20);
        waveformViewZ1.setYtitle("加速度模值(传感器3)");
        waveformViewZ1.setYRange(-20,20);
        waveformViewX2.setYtitle("加速度模值(传感器4)");
        waveformViewX2.setYRange(-20,20);
        waveformViewY2.setYtitle("加速度模值(传感器5)");
        waveformViewY2.setYRange(-20,20);
        waveformViewZ2.setYtitle("加速度模值(传感器6)");
        waveformViewZ2.setYRange(-20,20);
        if(startFlag==false){
            groupLayout.setVisibility(View.GONE);
        }else{
            groupLayout.setVisibility(View.VISIBLE);
        }
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                AlertDialog.Builder builder = new AlertDialog.Builder(XiangjiActivity.this);
//                builder.setTitle("请选择")
//                        .setItems(new String[]{"左手", "右手"}, (dialog, which) -> {
//                            if (which == 0) {
                waveformViewX1.clearDataPoints();
                waveformViewY1.clearDataPoints();
                waveformViewZ1.clearDataPoints();
                waveformViewX2.clearDataPoints();
                waveformViewY2.clearDataPoints();
                waveformViewZ2.clearDataPoints();
                                groupLayout.setVisibility(View.VISIBLE);
                                imageView.setVisibility(View.GONE);
                                shuomingText.setVisibility(View.GONE);
                                btn.setVisibility(View.GONE);
                                processorManager.setDeviceMac(deviceId.replace(":",""));
                                processorManager.temp=handDir;
                                processorManager.setDataUpdateListener(XiangjiActivity.this);
                                processorManager.startProcessing();
                                processorManager.setProcessingFunction(ProcessingFunction.WingBeatingPlus);

//                            } else {
//                                groupLayout.setVisibility(View.VISIBLE);
//                                imageView.setVisibility(View.GONE);
//                                shuomingText.setVisibility(View.GONE);
//                                btn.setVisibility(View.GONE);
//                                handDir = "R";
//                                processorManager.setDeviceMac(deviceId.replace(":",""));
//                                processorManager.temp=2;
//                                processorManager.setDataUpdateListener(XiangjiActivity.this);
//                                processorManager.startProcessing();
//                                processorManager.setProcessingFunction(ProcessingFunction.WingBeatingPlus);
//                            }
//                        })
//                        .setNegativeButton("取消", null)
//                        .show();
                Toast.makeText(XiangjiActivity.this, "开始测试", Toast.LENGTH_SHORT).show();
            }
        });



    }
    @Override
    protected void onStart() {
        super.onStart();
        Intent intent = new Intent(this, BluetoothService.class);
        intent.putExtra("DEVICE_ADDRESS", deviceId); // 如果需要
        bindService(intent, connection, Context.BIND_AUTO_CREATE);

    }
    @Override
    public void onDataProcessed(ProcessedData data) {
        String flag = data.getFlag();
        System.out.println("pingju-Flag:"+flag);
        if(flag.equals("allout")) {
            String processedValue = data.getAcccle();
            System.out.println("zhenchan-Hex: " + processedValue);
            //saveData.add(processedValue);
            String[] dataArr = processedValue.split(" ");   // 按逗号分割
            String da1x = dataArr[1].length()>10?dataArr[1].substring(0,8):dataArr[1];
            String da1y = dataArr[2].length()>10?dataArr[2].substring(0,8):dataArr[2];
            String da1z = dataArr[3].length()>10?dataArr[3].substring(0,8):dataArr[3];

            String da2x = dataArr[5].length()>10?dataArr[5].substring(0,8):dataArr[5];
            String da2y = dataArr[6].length()>10?dataArr[6].substring(0,8):dataArr[6];
            String da2z = dataArr[7].length()>10?dataArr[7].substring(0,8):dataArr[7];

            String da3x = dataArr[9].length()>10?dataArr[9].substring(0,8):dataArr[9];
            String da3y = dataArr[10].length()>10?dataArr[10].substring(0,8):dataArr[10];
            String da3z = dataArr[11].length()>10?dataArr[11].substring(0,8):dataArr[11];


            String da4x = dataArr[13].length()>10?dataArr[13].substring(0,8):dataArr[13];
            String da4y = dataArr[14].length()>10?dataArr[14].substring(0,8):dataArr[14];
            String da4z = dataArr[15].length()>10?dataArr[15].substring(0,8):dataArr[15];

            String da5x = dataArr[17].length()>10?dataArr[17].substring(0,8):dataArr[17];
            String da5y = dataArr[18].length()>10?dataArr[18].substring(0,8):dataArr[18];
            String da5z = dataArr[19].length()>10?dataArr[19].substring(0,8):dataArr[19];

            String da6x = dataArr[21].length()>10?dataArr[21].substring(0,8):dataArr[21];
            String da6y = dataArr[22].length()>10?dataArr[22].substring(0,8):dataArr[22];
            String da6z = dataArr[23].length()>10?dataArr[23].substring(0,8):dataArr[23];


            double magnitude = Math.sqrt(Float.parseFloat(da1x) * Float.parseFloat(da1x) + Float.parseFloat(da1y) * Float.parseFloat(da1y) + (Float.parseFloat(da1z)-9.8f) * (Float.parseFloat(da1z)-9.8f));
            double magnitude2 = Math.sqrt(Float.parseFloat(da2x) * Float.parseFloat(da2x) + Float.parseFloat(da2y) * Float.parseFloat(da2y) + (Float.parseFloat(da2z)-9.8f) * (Float.parseFloat(da2z)-9.8f));
            double magnitude3 = Math.sqrt(Float.parseFloat(da3x) * Float.parseFloat(da3x) + Float.parseFloat(da3y) * Float.parseFloat(da3y) + (Float.parseFloat(da3z)-9.8f) * (Float.parseFloat(da3z)-9.8f));
            double magnitude4 = Math.sqrt(Float.parseFloat(da4x) * Float.parseFloat(da4x) + Float.parseFloat(da4y) * Float.parseFloat(da4y) + (Float.parseFloat(da4z)-9.8f) * (Float.parseFloat(da4z)-9.8f));
            double magnitude5 = Math.sqrt(Float.parseFloat(da5x) * Float.parseFloat(da5x) + Float.parseFloat(da5y) * Float.parseFloat(da5y) + (Float.parseFloat(da5z)-9.8f) * (Float.parseFloat(da5z)-9.8f));
            double magnitude6 = Math.sqrt(Float.parseFloat(da6x) * Float.parseFloat(da6x) + Float.parseFloat(da6y) * Float.parseFloat(da6y) + (Float.parseFloat(da6z)-9.8f) * (Float.parseFloat(da6z)-9.8f));

            waveformViewX1.addDataPoint((float)magnitude);
            waveformViewY1.addDataPoint((float)magnitude2);
            waveformViewZ1.addDataPoint((float)magnitude3);
            waveformViewX2.addDataPoint((float)magnitude4);
            waveformViewY2.addDataPoint((float)magnitude5);
            waveformViewZ2.addDataPoint((float)magnitude6);


        }
        if(flag.equals("success")){
            SharedPreferences sp = getSharedPreferences("my_cache", MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            editor.putBoolean("isXiangji", true);
            editor.apply();
            Toast.makeText(XiangjiActivity.this,"测试完成",Toast.LENGTH_SHORT).show();
           // utils.writeToFile(saveData.toString(),"xiangnei.txt");
            finish();

        }
    }
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish(); // 结束当前Activity，返回上一个
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}